package com.bee.beemanage.system.configs.SecurityConfigs;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bee.beemanage.api.entity.SysUserLogin;
import com.bee.beemanage.api.mapper.SysUserLoginMapper;
import com.bee.beemanage.system.common.utils.redis.RedisUtils;
import com.bee.beemanage.system.common.utils.result.Result;
import com.bee.beemanage.system.common.utils.result.ResultCode;
import com.bee.beemanage.system.common.utils.result.ResultTool;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description:
 * @author: chenguosong
 * @date: 2022-10-18 08:52
 */
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private RedisUtils redisUtils;
    @Resource
    private SysUserLoginMapper sysUserLoginMapper;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String tokenInfo = request.getHeader("Authorization");
        String bearer = tokenInfo.replace("Bearer ", "");
        redisUtils.del("LoginUsers:"+bearer);
        QueryWrapper<SysUserLogin> wrapper = new QueryWrapper<>();
        wrapper.eq("token",bearer);
        SysUserLogin loginUser = sysUserLoginMapper.selectOne(wrapper);
        if(null!=loginUser){
            sysUserLoginMapper.delete(wrapper);
        }
        Result result = ResultTool.success(ResultCode.SUCCESS);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(result));
    }
}
